package icu.groot.alan.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import icu.groot.alan.entity.TokenEntity;
import icu.groot.alan.service.UserService;
import icu.groot.alan.service.impl.UserServiceImpl;
import icu.groot.alan.util.R;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

@WebFilter(urlPatterns = {
        "/department/deleted.do",
        "/department/add.do",
        "/user/add.do",
        "/user/deleted.do",
        "/announce/announce.do",
        "/report/export/excel.export"
})
public class FilterC_Admin implements Filter {
    Logger logger = Logger.getLogger("icu.groot.alan.filter.AdminFilter");

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        logger.info("进入Admin过滤器");

        ObjectMapper objectMapper = new ObjectMapper();
        System.out.println(servletRequest.getAttribute("tokenEntity").toString());
        TokenEntity tokenEntity = (TokenEntity) servletRequest.getAttribute("tokenEntity");
        //校验token里面的数据
        if (tokenEntity == null || StringUtils.isAnyBlank(tokenEntity.getCode())){
            servletResponse.getWriter().print(objectMapper.writeValueAsString(R.error("token异常")));
            return;
        }
        logger.info("管理员token验证通过" + tokenEntity.toString());
        //拿着id去数据库查找身份
        UserService userService = new UserServiceImpl();
        List<String> department = null;
        try{
            department = userService.getDepartmentByCode(Integer.parseInt(tokenEntity.getCode()));
        }catch (Exception e){
            e.printStackTrace();
            logger.info("token异常");
            servletResponse.getWriter().print(objectMapper.writeValueAsString(R.error("token异常")));
            return;
        }
        logger.info("管理员身份核对通过" + department.get(0).toString());
        if (department.isEmpty() || !department.get(0).equals("管理员")){
            logger.info("核对管理员身份失败");
            servletResponse.getWriter().print(objectMapper.writeValueAsString(R.error("身份权限不够，无法操作")));
            return;
        }

        logger.info("管理员身份核对成功");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
